package com.micro.shop.controller;

import java.util.List;
import java.util.UUID;

import me.chanjar.weixin.common.exception.WxErrorException;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.api.impl.WxMaUserServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;

import com.micro.shop.config.WxConfig;
import com.micro.shop.core.ApiResponse;
import com.micro.shop.mapper.UserMapper;
import com.micro.shop.model.User;
import com.micro.shop.model.UserCriteria;
import com.micro.shop.redis.RedisWechatApptoken;
import com.micro.shop.vo.UserTokenInfoVo;
/**
 * 微信小程序控制器
 *
 */
@Controller
@RequestMapping("/wxapp")
public class MiniAppController {

	@Autowired
	WxConfig wxConfig;
	
	@Autowired
	UserMapper userMapper;
	
	@Autowired
	RedisWechatApptoken redisWechatApptoken;
	
	@RequestMapping("/login")
	@ResponseBody
	public ApiResponse<String> getUserInfo(String code) {
		ApiResponse<String> loginTokenResponse = new ApiResponse<String>();
		WxMaInMemoryConfig wxMaConfig = new WxMaInMemoryConfig();
		wxMaConfig.setAppid(wxConfig.getAppid());
		wxMaConfig.setSecret(wxConfig.getSecret());
		wxMaConfig.setToken(wxConfig.getToken());
		WxMaService wxMaService = new WxMaServiceImpl();
		wxMaService.setWxMaConfig(wxMaConfig);
		WxMaUserService wxMaUserService = new WxMaUserServiceImpl(wxMaService);
		UserTokenInfoVo userToken = new  UserTokenInfoVo();
		Integer userId = null;
		User user;
		try {
			WxMaJscode2SessionResult userInfo = wxMaUserService.getSessionInfo(code);
			UserCriteria userCriteriaQuery = new UserCriteria();
			userCriteriaQuery.createCriteria().andOpenidEqualTo(userInfo.getOpenid());
			List<User> userList = userMapper.selectByExample(userCriteriaQuery);
			if(CollectionUtils.isEmpty(userList)){
				return loginTokenResponse.setCode("5000");
			}
			user = userList.get(0);
		} catch (WxErrorException e) {
			e.printStackTrace();
			return loginTokenResponse.setCode("5000");
		}
		userId = user.getUid();
		userToken.setUserId(userId); 
		String token = generateToken();
		redisWechatApptoken.createMemberToken(token, userToken,7*24*60*60);
		return loginTokenResponse.setData(token);
	}
	
	
	@RequestMapping("/register/complex")
	@ResponseBody
	public ApiResponse<Boolean> registerComplex(String code,String encryptedData,String iv) {
		
		ApiResponse<Boolean> registerResponse = new ApiResponse<Boolean>();
		WxMaInMemoryConfig wxMaConfig = new WxMaInMemoryConfig();
		wxMaConfig.setAppid(wxConfig.getAppid());
		wxMaConfig.setSecret(wxConfig.getSecret());
		wxMaConfig.setToken(wxConfig.getToken());
		WxMaService wxMaService = new WxMaServiceImpl();
		wxMaService.setWxMaConfig(wxMaConfig);
		WxMaUserService wxMaUserService = new WxMaUserServiceImpl(wxMaService);
		
		try {
			WxMaJscode2SessionResult userInfo = wxMaUserService.getSessionInfo(code);
			WxMaUserInfo wxUserInfo = wxMaUserService.getUserInfo(userInfo.getSessionKey(), encryptedData, iv);
			
			UserCriteria userCriteriaQuery = new UserCriteria();
			userCriteriaQuery.createCriteria().andOpenidEqualTo(userInfo.getOpenid());
			User user = new User();
			user.setIsWeixin(1);
			user.setAvatar(wxUserInfo.getAvatarUrl());
			user.setNickname(wxUserInfo.getNickName());
			user.setOpenid(userInfo.getOpenid());
			user.setSessionId(userInfo.getSessionKey());
			userMapper.insertSelective(user);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		registerResponse.setData(true);
		return registerResponse;
	}
	@RequestMapping("/check-token")
	@ResponseBody
	public  ApiResponse<String> checkToken(String token) {
		 ApiResponse<String> tokenResponse = new ApiResponse<String>();
		return tokenResponse;
	}
	private String generateToken(){
		return UUID.randomUUID().toString().replace("-", "");
	}
}
